<?php

namespace App\Http\Services;

use App\Exceptions\ServiceException;
use App\Exceptions\ServiceExceptionConstant;
use App\Http\Repositories\Daos\Good\GoodsCycleDao;
use App\Http\Repositories\Daos\Good\GoodsDao;
use App\Http\Requests\UserContext;
use App\Http\Traits\GlobalConstant;

class GoodsService extends BaseService
{
    protected $goodsDao;
    protected $goodsCycleDao;

    public function __construct(GoodsDao $goodsDao, GoodsCycleDao $goodsCycleDao)
    {
        $this->goodsDao      = $goodsDao;
        $this->goodsCycleDao = $goodsCycleDao;
    }

    public function lists(UserContext $userContext)
    {
        $orderKeyStr = request('order_key_str') ?? '';
        $condition   = [
            'status' => 1,
        ];
        if (!empty($kind)) {
            $condition['kind'] = $kind;
        }
        $page       = request('page') ?? 1;
        $size       = request('size') ?? 10;
        $field      = ['id', 'name', 'icon', 'desc', 'price'];
        $orderArray = explode(GlobalConstant::DELIMITER_CHARACTER, $orderKeyStr);
        $order      = [];
        switch ($orderArray[0]) {
            case 'price':
                $order['price'] = $orderArray[1];
                break;
            case 'time':
                $order['created_at'] = $orderArray[1];
                break;
            default:
                break;
        }
        $count = $this->goodsDao->count($condition);
        $list  = $this->goodsDao->getListPage($condition, $field, $page, $size, $order);
        return compact("list", "count");

    }

    public function detail(UserContext $userContext)
    {
        $userId    = $userContext->getId();
        $gId = request('g_id') ?? 0;
        $qty       = request('qty') ?? 0;
        $detail    = $this->goodsDao->getOne(['id' => $gId, 'status' => 1]);
        if (!$detail) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('goods_invalid'));
        }
        return $detail;
    }

    public function cycle()
    {
        $gId = request('g_id') ?? 0;
        if (empty($gId)) {
            throw new ServiceException(ServiceExceptionConstant::getErrorData('goods_invalid'));
        }
        $condition['g_id']   = $gId;
        $condition['status'] = 1;
        $field               = ['id', 'g_id', 'title', 'price'];
        return $this->goodsCycleDao->getListPage($condition, $field);
    }

}
